package com.foreveredu.erlms.web.struts.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.foreveredu.erlms.domain.Clazz;
import com.foreveredu.erlms.domain.Department;
import com.foreveredu.erlms.domain.Enroll;
import com.foreveredu.erlms.domain.Examinee;

import com.foreveredu.erlms.domain.Parameter;
import com.foreveredu.erlms.domain.Rank;
import com.foreveredu.erlms.service.IExamService;
import com.foreveredu.erlms.service.IManagementService;
import com.foreveredu.erlms.web.struts.actionform.EnrollActionForm;

/*
 * @author hushigang 2012/4/14
 * EnrollAction负责处理考生报名业务请求
 */
public class EnrollAction extends AbstractBaseDispatchAction {

	private IExamService examService = null;
	private IManagementService managementService = null;

	public IExamService getExamService() {
		return examService;
	}

	public void setExamService(IExamService examService) {
		this.examService = examService;
	}

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	Logger log = Logger.getLogger(EnrollAction.class);
	
	// 跳转到报名页面
	public ActionForward toEnroll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 将当前有效的考试等级及语言列表显示在报名页面中
		List<Rank> rankList = examService.findRanksOfEnabled();
		request.setAttribute("rankList", rankList);

		// 将院系列表显示在报名页面中
		List<Department> deptList = managementService.findDepartments();
		request.setAttribute("deptList", deptList);

		return mapping.findForward("toEnroll");
	}

	// 跳转到补考报名页面
	public ActionForward toResitEnroll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 将当前有效的考试等级及语言列表显示在报名页面中
		List<Rank> rankList = examService.findRanksOfEnabled();
		//在补考等级列表中去掉一级选项
		rankList.remove(examService.findRankByCode("15"));
		request.setAttribute("rankList", rankList);

		// 将院系列表显示在报名页面中
		List<Department> deptList = managementService.findDepartments();
		// 在补考等级列表中去掉一级选项
		request.setAttribute("deptList", deptList);

		return mapping.findForward("toResitEnroll");
	}

	// 提交报名信息
	@SuppressWarnings("unchecked")
	public ActionForward saveEnroll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		EnrollActionForm enrollForm = (EnrollActionForm) form;

		// 读取系统参数，是否允许报名
		Parameter param = examService.getParameterOfNow();

		if (param.getIsEnrollPermitted() == 0) {
			request.setAttribute("notPermittedEnrollError",
					"网络报名系统暂未开放，请联系管理员！");
			return mapping.findForward("saveEnroll");
		}
		//获取当前考次
		int examOrder = examService.getExamOrderOfNow();

		// 将当前有效的考试等级及语言列表显示在报名页面中
		List<Rank> rankList = examService.findRanksOfEnabled();
		request.setAttribute("rankList", rankList);

		// 将院系列表显示在报名页面中
		List<Department> deptList = managementService.findDepartments();
		request.setAttribute("deptList", deptList);

		// 表单校验
		// 报考等级语言未选择
		if (enrollForm.getRank_id() == 0) {
			request.setAttribute("rank_idEmptyError", "请选择报考等级及语言！");
			
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			
			return mapping.findForward("toEnroll");
		}

		// 未输入身份证号码
		if (enrollForm.getIdCard() == null || enrollForm.getIdCard().equals("")) {
			request.setAttribute("idCardEmptyError", "请输入身份证号码！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		} else {
			// 对输入的身份证号码进行校验
			Pattern p = Pattern
					.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z|a-z])$");
			Matcher m = p.matcher(enrollForm.getIdCard());
			if (!m.matches()) {
				request.setAttribute("IDCardError", "身份证号码输入有误！");
				//将用户选择的班级数据发送到报名页面
				List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
				request.setAttribute("clazzList", clazzList);
				return mapping.findForward("toEnroll");
			}
		}
		
		//判断用户是否重复报名，37次考试只允许考生报考一个科目
//		if(examService.findEnrollByDeptAndIdCard(examOrder ,enrollForm.getIdCard() ,enrollForm.getRank_id() )){
		Examinee exist = examService.findExamineeByIdCard(enrollForm.getIdCard(), examOrder);
		if (exist != null) {
			request.setAttribute("IdCardAgain", "每次考试只允许报考一个科目！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		}
		
		// 未输入姓名
		if (enrollForm.getName() == null || enrollForm.getName().equals("")) {
			request.setAttribute("nameEmptyError", "请输入姓名！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		}

		// 未选择性别
		if (enrollForm.getSex() == 0) {
			request.setAttribute("sexEmptyError", "请选择性别！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		}

		// 出生日期验证
		if (enrollForm.getBirthday() == null
				|| enrollForm.getBirthday().equals("")) {
			request.setAttribute("BirthdayEmptyError", "请输入8位出生日期！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		} else {
			Pattern p = Pattern.compile("\\d{8}");
			Matcher m = p.matcher(enrollForm.getBirthday());
			if (!m.matches()) {
				request.setAttribute("BirthdayInputError",
						"请输入8位出生日期，例如19920608！");
				//将用户选择的班级数据发送到报名页面
				List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
				request.setAttribute("clazzList", clazzList);
				return mapping.findForward("toEnroll");
			}
		}
		// 民族验证
		if (enrollForm.getNation().equals("0")) {
			request.setAttribute("nationEmptyError", "请选择民族！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		}

		// 职业验证
		if (enrollForm.getProfession().equals("0")) {
			request.setAttribute("professionEmptyError", "请选择职业！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		}

		// 文化程度验证
		if (enrollForm.getDegree().equals("0")) {
			request.setAttribute("degreeEmptyError", "请选择文化程度！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		}

		// 电话（手机号码）验证
		if (enrollForm.getPhone() == null || enrollForm.getPhone().equals("")) {
			request.setAttribute("PhoneEmptyError", "请输入手机号码！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		} else {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			Matcher m = p.matcher(enrollForm.getPhone());
			if (!m.matches()) {
				request.setAttribute("PhoneInputError", "你输入手机号码错误！");
				//将用户选择的班级数据发送到报名页面
				List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
				request.setAttribute("clazzList", clazzList);
				return mapping.findForward("toEnroll");
			}
		}

		// 联系地址（所在院系）验证
		if (enrollForm.getDeptId() == 0) {
			request.setAttribute("dept_idEmptyError", "请选择所在院系）！");
			return mapping.findForward("toEnroll");
		}

		// 班级验证
		if (enrollForm.getClazzId() == 0) {
			request.setAttribute("clazzEmptyError", "请选择所在班级！");
			//将用户选择的班级数据发送到报名页面
			List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
			request.setAttribute("clazzList", clazzList);
			return mapping.findForward("toEnroll");
		} 

		//保存考生照片文件名
		String icon = null;
		//保存考生网报号
		String serialNumber = null;
		
		// 将考生上传照片保存到photo文件夹中
		String dirPath = request.getSession().getServletContext().getRealPath("/photo");

		// 判断路径是否存在，如果不存在，就创建这个路径
		File fileDir = new File(dirPath);
		if (!fileDir.exists()) {
			fileDir.mkdir();
		}
		
		// 获取文件并存储
		Hashtable<Object, Object> files = form.getMultipartRequestHandler()
				.getFileElements();
		for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();

			try {
				FormFile formFile = (FormFile) files.get(key);
				String fileName = formFile.getFileName().trim();// 获得待上传的文件名

				if (fileName == null || fileName.equals("")) {
					request.setAttribute("imageEmptyError", "请按要求上传照片！");
					
					//将用户选择的班级数据发送到报名页面
					List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
					request.setAttribute("clazzList", clazzList);
					
					return mapping.findForward("toEnroll");
				}

				// 读出原文件的扩展名
				String ext = "";
				int pos = fileName.lastIndexOf(".");
				ext = fileName.substring(pos);// 得到扩展名

				if (!ext.equalsIgnoreCase(".jpg")) {
					request.setAttribute("imgFormatError", "照片格式不对，只能是jpg格式！");
					
					//将用户选择的班级数据发送到报名页面
					List clazzList = managementService.findClazzsByDept(enrollForm.getDeptId());
					request.setAttribute("clazzList", clazzList);
					
					return mapping.findForward("toEnroll");
				}

				// 待所有输入数据，包括考生相片检测无误后，自动生成考生网报号
				serialNumber = examService.getMaxSNRecord();
				
				// 保存后的文件名不能使用原来的,可以防止下载出错
				// 新文件名为网报号，待考生交费确认后，将文件名改为报名号
				String newFileName = serialNumber;
				
				// 拼出完整的新文件名
				// newFileName = datetime + newFileName +
				// ext;//暂时先将报名号作为上传相片的文件名
				newFileName = newFileName + ext;
				icon = newFileName;

				InputStream is = formFile.getInputStream();
				OutputStream os = new FileOutputStream(dirPath
						+ File.separatorChar + newFileName);

				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
				}
				os.flush();

				is.close();
				os.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}
		
		// 当报名信息提交时，创建考生对象，
		Examinee examinee = new Examinee();
		examinee.setIdCard(enrollForm.getIdCard());
		examinee.setExamOrder(examOrder);
		
		// 获得考生报考等级信息
		Rank rank = examService.findRankById(enrollForm.getRank_id());

		// 获得学校代码
		//String schoolCode = examService.getSchoolCode();
		// 自动生成考生报名号
		// String maxEnrollNumber = examService.getMaxEnrollNumber(schoolCode,
		// rank.getCode(), examOrder);
		// examinee.setEnrollNumber(maxEnrollNumber);

		// 自动生成考生网报号
		//String serialNumber = examService.getMaxSerialNumber(schoolCode, examOrder);
		
		examinee.setSerialNumber(serialNumber);

		// 创建报名信息对象
		Enroll enroll = new Enroll();
		PropertyUtils.copyProperties(enroll, enrollForm);
		
		//去掉姓名前后的空格
		enroll.setName(enrollForm.getName().trim());
		enroll.setExaminee(examinee);
		enroll.setRank(rank);
		enroll.setIsPaid(0);// 考生提交报名信息时，默认为未交费状态，财务管理员可修改考生交费状态信息

		// 获得考生所在院系
		Department dept = managementService.findDepartmentById(enrollForm.getDeptId());
		enroll.setDept(dept);
		
		//获得考生所在班级
		Clazz clazz = managementService.findClazzById(enrollForm.getClazzId());
		enroll.setClazz(clazz);
		
		// 保存报名信息对象
		enroll.setIcon(icon);
		//将当前日期储存到enroll中
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String now = sdf.format(new Date());
		enroll.setLoginTime(now);
		examService.saveEnroll(enroll);

		// 保存考生对象
		examinee.setEnroll(enroll);
		examService.saveExaminee(examinee);
		
		// 将考生姓名和报名号发送到报名成功页面
		request.setAttribute("name", enrollForm.getName().trim());
		request.setAttribute("serialNumber", serialNumber);
		request.setAttribute("rank", rank.getName());
		request.setAttribute("idCard", enrollForm.getIdCard());

		request.setAttribute("sex", enrollForm.getSex() == 1 ? "男" : "女");
		request.setAttribute("birthday", enrollForm.getBirthday());
		request.setAttribute("nation", enrollForm.getNation());
		request.setAttribute("profession", enrollForm.getProfession());
		request.setAttribute("degree", enrollForm.getDegree());
		request.setAttribute("phone", enrollForm.getPhone());
		request.setAttribute("department", dept.getDeptName());
		request.setAttribute("clazz", clazz.getClazzId());

		return mapping.findForward("saveEnroll");
	}

	// 提交补考报名信息
	@SuppressWarnings("unchecked")
	public ActionForward saveResitEnroll(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		EnrollActionForm enrollForm = (EnrollActionForm) form;

		// 读取系统参数，是否允许报名
		Parameter param = examService.getParameterOfNow();

		if (param.getIsEnrollPermitted() == 0) {
			request.setAttribute("notPermittedEnrollError",
					"网络报名系统暂未开放，请联系管理员！");
			return mapping.findForward("saveEnroll");
		}

		// 将当前有效的考试等级及语言列表显示在报名页面中
		List<Rank> rankList = examService.findRanksOfEnabled();
		// 在补考等级列表中去掉一级选项
		rankList.remove(examService.findRankByCode("15"));
		request.setAttribute("rankList", rankList);

		// 将院系列表显示在报名页面中
		List<Department> deptList = managementService.findDepartments();
		request.setAttribute("deptList", deptList);

		// 表单校验
		// 报考等级语言未选择
		if (enrollForm.getRank_id() == 0) {
			request.setAttribute("rank_idEmptyError", "请选择报考等级及语言");
			return mapping.findForward("toResitEnroll");
		} else {// 一级不存在补考
			Rank rank = examService.findRankById(enrollForm.getRank_id());
			if (rank.getCode().equals("15")) {
				request.setAttribute("rankResitError",
						"一级考试不存在补考，请直接点击【网络报名】菜单报考一级考试！");
				return mapping.findForward("toResitEnroll");
			}
		}

		// 未输入身份证号码
		if (enrollForm.getIdCard() == null || enrollForm.getIdCard().equals("")) {
			request.setAttribute("idCardEmptyError", "请输入身份证号码");
			return mapping.findForward("toResitEnroll");
		} else {
			// 对输入的身份证号码进行校验
			Pattern p = Pattern
					.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z|a-z])$");
			Matcher m = p.matcher(enrollForm.getIdCard());
			if (!m.matches()) {
				request.setAttribute("IDCardError", "身份证号码输入有误！");
				return mapping.findForward("toResitEnroll");
			}
		}

		// 未输入姓名
		if (enrollForm.getName() == null || enrollForm.getName().equals("")) {
			request.setAttribute("nameEmptyError", "请输入姓名！");
			return mapping.findForward("toResitEnroll");
		}

		// 未选择性别
		if (enrollForm.getSex() == 0) {
			request.setAttribute("sexEmptyError", "请选择性别！");
			return mapping.findForward("toResitEnroll");
		}

		// 出生日期验证
		if (enrollForm.getBirthday() == null
				|| enrollForm.getBirthday().equals("")) {
			request.setAttribute("BirthdayEmptyError", "请输入8位出生日期！");
			return mapping.findForward("toResitEnroll");
		} else {
			Pattern p = Pattern.compile("\\d{8}");
			Matcher m = p.matcher(enrollForm.getBirthday());
			if (!m.matches()) {
				request.setAttribute("BirthdayInputError",
						"请输入8位出生日期，例如19920608！");
				return mapping.findForward("toResitEnroll");
			}
		}
		// 民族验证
		if (enrollForm.getNation().equals("0")) {
			request.setAttribute("nationEmptyError", "请选择民族！");
			return mapping.findForward("toResitEnroll");
		}

		// 职业验证
		if (enrollForm.getProfession().equals("0")) {
			request.setAttribute("professionEmptyError", "请选择职业！");
			return mapping.findForward("toResitEnroll");
		}

		// 文化程度验证
		if (enrollForm.getDegree().equals("0")) {
			request.setAttribute("degreeEmptyError", "请选择文化程度！");
			return mapping.findForward("toResitEnroll");
		}

		// 补考类型验证
		if (enrollForm.getKeepGradeType() == 0) {
			request.setAttribute("resitEmptyError", "请选择补考类型！");
			return mapping.findForward("toResitEnroll");
		}

		// 补考考生需输入原准考证号
		if (enrollForm.getOldTicketNumber() == null
				|| enrollForm.getOldTicketNumber().equals("")) {
			request.setAttribute("OldTicketNumberEmptyError", "补考考生请输入原准考证号！");
			return mapping.findForward("toResitEnroll");
		} else {
			Pattern p = Pattern.compile("\\d{16}");
			Matcher m = p.matcher(enrollForm.getOldTicketNumber());
			if (!m.matches()) {
				request.setAttribute("OldTicketNumberInputError",
						"请输入16位的原准考证号！");
				return mapping.findForward("toResitEnroll");
			}
		}

		// 电话（手机号码）验证
		if (enrollForm.getPhone() == null || enrollForm.getPhone().equals("")) {
			request.setAttribute("PhoneEmptyError", "请输入手机号码！");
			return mapping.findForward("toResitEnroll");
		} else {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			Matcher m = p.matcher(enrollForm.getPhone());
			if (!m.matches()) {
				request.setAttribute("PhoneInputError", "你输入手机号码错误！");
				return mapping.findForward("toResitEnroll");
			}
		}

		// 联系地址（所在院系）验证
		if (enrollForm.getDeptId() == 0) {
			request.setAttribute("dept_idEmptyError", "请输入联系地址（所在院系）！");
			return mapping.findForward("toResitEnroll");
		}

		// 班级验证
		if (enrollForm.getClazzId() == 0) {
			request.setAttribute("clazzEmptyError", "请选择所在班级！");
			return mapping.findForward("toResitEnroll");
		} 
		
		// 当报名信息提交时，创建考生对象，
		Examinee examinee = new Examinee();
		examinee.setIdCard(enrollForm.getIdCard());

		// 获得考生报考等级信息
		Rank rank = examService.findRankById(enrollForm.getRank_id());

		// 获得学校代码和当前考试届次
		String schoolCode = examService.getSchoolCode();
		int examOrder = examService.getExamOrderOfNow();
		examinee.setExamOrder(examOrder);

		// // 自动生成考生报名号
		// String maxEnrollNumber = examService.getMaxEnrollNumber(schoolCode,
		// rank.getCode(), examOrder);
		// examinee.setEnrollNumber(maxEnrollNumber);

		// 自动生成考生网报号
		String serialNumber = examService.getMaxSNRecord();
		examinee.setSerialNumber(serialNumber);

		// 创建报名信息对象
		Enroll enroll = new Enroll();
		PropertyUtils.copyProperties(enroll, enrollForm);
		
		//去掉姓名前后的空格
		enroll.setName(enrollForm.getName().trim());
		
		enroll.setExaminee(examinee);
		enroll.setRank(rank);
		enroll.setIsPaid(0);// 考生提交报名信息时，默认为未交费状态，财务管理员可修改考生交费状态信息

		// 获得考生所在院系
		Department dept = managementService.findDepartmentById(enrollForm
				.getDeptId());
		enroll.setDept(dept);

		// 将考生上传照片保存到photo文件夹中
		String dirPath = request.getSession().getServletContext()
				.getRealPath("/photo");

		// 判断路径是否存在，如果不存在，就创建这个路径
		File fileDir = new File(dirPath);
		if (!fileDir.exists()) {
			fileDir.mkdir();
		}

		// 获取文件并存储
		String icon = null;
		Hashtable<Object, Object> files = form.getMultipartRequestHandler()
				.getFileElements();
		for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();

			try {
				FormFile formFile = (FormFile) files.get(key);
				String fileName = formFile.getFileName().trim();// 获得待上传的文件名

				if (fileName == null || fileName.equals("")) {
					request.setAttribute("imageEmptyError", "请按要求上传照片！");
					return mapping.findForward("toResitEnroll");
				}

				// 保存后的文件名不能使用原来的,可以防止下载出错
				// 新文件名为网报号，待考生交费确认后，将文件名改为报名号
				String newFileName = serialNumber;

				// 获得当天日期
				// Date date = new Date();
				// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				// String datetime = sdf.format(date);

				// 读出原文件的扩展名
				String ext = "";
				int pos = fileName.lastIndexOf(".");
				ext = fileName.substring(pos);// 得到扩展名

				if (!ext.equalsIgnoreCase(".jpg")) {
					request.setAttribute("imgFormatError", "照片格式不对，只能是jpg格式！");
					return mapping.findForward("toResitEnroll");
				}

				// 拼出完整的新文件名
				// newFileName = datetime + newFileName +
				// ext;//暂时先将报名号作为上传相片的文件名
				newFileName = newFileName + ext;
				icon = newFileName;

				InputStream is = formFile.getInputStream();
				OutputStream os = new FileOutputStream(dirPath
						+ File.separatorChar + newFileName);

				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
				}
				os.flush();

				is.close();
				os.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}

		

		// 保存报名信息对象
		enroll.setIcon(icon);
		//将当前日期储存到enroll中
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String now = sdf.format(new Date());
		enroll.setLoginTime(now);
		examService.saveEnroll(enroll);

		// 保存考生对象
		examinee.setEnroll(enroll);
		examService.saveExaminee(examinee);
		// 将考生姓名和报名号发送到报名成功页面
		request.setAttribute("name", enrollForm.getName().trim());
		request.setAttribute("serialNumber", serialNumber);
		request.setAttribute("rank", rank.getName());
		request.setAttribute("idCard", enrollForm.getIdCard());

		request.setAttribute("sex", enrollForm.getSex() == 1 ? "男" : "女");
		request.setAttribute("birthday", enrollForm.getBirthday());
		request.setAttribute("nation", enrollForm.getNation());
		request.setAttribute("profession", enrollForm.getProfession());
		request.setAttribute("degree", enrollForm.getDegree());
		request.setAttribute("phone", enrollForm.getPhone());
		request.setAttribute("department", dept.getDeptName());
		request.setAttribute("clazz", enrollForm.getClazzId());

		return mapping.findForward("saveEnroll");
	}

	// 跳转到查询报名信息页面
	public ActionForward findEnroll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("findEnroll");
	}

	// 通过身份证号码和网报号查找报名信息，并跳转到编辑报名信息页面
	public ActionForward editEnroll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		EnrollActionForm enrollForm = (EnrollActionForm) form;

		// // 通过身份证号码和报名号查找报名信息
		// Enroll enroll = examService.findEnrollByIdCardAndEnrollNumber(
		// enrollForm.getIdCard(), enrollForm.getEnrollNumber());

		// 通过身份证号码和网报号查找报名信息
		Enroll enroll = examService.findEnrollByIdCardAndSerialNumber(
				enrollForm.getIdCard(), enrollForm.getSerialNumber(),
				examService.getExamOrderOfNow());

		if (enroll == null) {
			request.setAttribute("errMsg", "身份证号码或网报号错误，请重新输入！");
			return mapping.findForward("findEnroll");
		}

		// 考生交费确认报名信息后，将不能再修改报名信息
		if (enroll.getIsPaid() == 1
				&& enroll.getExaminee().getEnrollNumber() != null) {
			request.setAttribute("errMsg", "你已交费并确认报名信息，不能再修改报名信息！");
			return mapping.findForward("findEnroll");
		}

		// 将报名信息发送到编辑页面
		PropertyUtils.copyProperties(enrollForm, enroll);
		request.setAttribute("enroll", enroll);

		// 将当前有效的考试等级及语言列表显示在报名页面中
		List<Rank> rankList = examService.findRanksOfEnabled();
		request.setAttribute("rankList", rankList);

		// 将院系列表显示在报名页面中
		List<Department> deptList = managementService.findDepartments();
		request.setAttribute("deptList", deptList);

		// 将班级信息发送到编辑页面
		List clazzList = managementService.findClazzsOfDepartment(enroll.getDept());
		request.setAttribute("clazzList", clazzList);
		
		return mapping.findForward("editEnroll");
	}

	// 完成报名信息的修改操作
	@SuppressWarnings("unchecked")
	public ActionForward updateEnroll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		EnrollActionForm enrollForm = (EnrollActionForm) form;

		// 读取系统参数，是否允许修改报名信息
		Parameter param = examService.getParameterOfNow();

		if (param != null && param.getIsEditEnrollPermitted() == 0) {
			request.setAttribute("notPermittedEditEnrollError",
					"系统当前禁止修改报名信息，请联系管理员！");
			return mapping.findForward("updateEnrollSave");
		}

		// 获得考生完整报名信息，以便修改
		Enroll enroll = examService.findEnrollById(enrollForm.getId());
		enrollForm.setIcon(enroll.getIcon());
		
		// 将当前有效的考试等级及语言列表显示在报名页面中
		List<Rank> rankList = examService.findRanksOfEnabled();
		request.setAttribute("rankList", rankList);

		// 将院系列表显示在报名页面中
		List<Department> deptList = managementService.findDepartments();
		request.setAttribute("deptList", deptList);

		// 将班级信息发送到编辑页面
		List clazzList = managementService.findClazzsOfDepartment(enroll.getDept());
		request.setAttribute("clazzList", clazzList);
		
		// 表单校验
		// 报考等级语言未选择
		if (enrollForm.getRank_id() == 0) {
			request.setAttribute("rank_idEmptyError", "请选择报考等级及语言");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		}

		// 未输入身份证号码
		if (enrollForm.getIdCard() == null || enrollForm.getIdCard().equals("")) {
			request.setAttribute("idCardEmptyError", "请输入身份证号码");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		} else {
			// 对输入的身份证号码进行校验
			Pattern p = Pattern
					.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z|a-z])$");
			Matcher m = p.matcher(enrollForm.getIdCard());
			if (!m.matches()) {
				request.setAttribute("IDCardError", "身份证号码输入有误！");
				request.setAttribute("enroll", enroll);
				return mapping.findForward("editEnroll");
			}
		}

		// 未输入姓名
		if (enrollForm.getName() == null || enrollForm.getName().equals("")) {
			request.setAttribute("nameEmptyError", "请输入姓名！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		}

		// 未选择性别
		if (enrollForm.getSex() == 0) {
			request.setAttribute("sexEmptyError", "请选择性别！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		}

		// 出生日期验证
		if (enrollForm.getBirthday() == null
				|| enrollForm.getBirthday().equals("")) {
			request.setAttribute("BirthdayEmptyError", "请输入8位出生日期！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		} else {
			Pattern p = Pattern.compile("\\d{8}");
			Matcher m = p.matcher(enrollForm.getBirthday());
			if (!m.matches()) {
				request.setAttribute("BirthdayInputError",
						"请输入8位出生日期，例如19920608！");
				request.setAttribute("enroll", enroll);
				return mapping.findForward("editEnroll");
			}
		}
		// 民族验证
		if (enrollForm.getNation().equals("0")) {
			request.setAttribute("nationEmptyError", "请选择民族！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		}

		// 职业验证
		if (enrollForm.getProfession().equals("0")) {
			request.setAttribute("professionEmptyError", "请选择职业！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		}

		// 文化程度验证
		if (enrollForm.getDegree().equals("0")) {
			request.setAttribute("degreeEmptyError", "请选择文化程度！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		}

		//第37次考试取消补考
//		// 补考考生需输入原准考证号
//		if (enrollForm.getKeepGradeType() != 0) {
//			if (enrollForm.getOldTicketNumber() == null
//					|| enrollForm.getOldTicketNumber().equals("")) {
//				request.setAttribute("OldTicketNumberEmptyError",
//						"补考考生请输入原准考证号！");
//				request.setAttribute("enroll", enroll);
//				return mapping.findForward("editEnroll");
//			} else {
//				Pattern p = Pattern.compile("\\d{16}");
//				Matcher m = p.matcher(enrollForm.getOldTicketNumber());
//				if (!m.matches()) {
//					request.setAttribute("OldTicketNumberInputError",	"请输入16位的原准考证号！");
//					request.setAttribute("enroll", enroll);
//					return mapping.findForward("editEnroll");
//				}
//			}
//		} else {
//			if (enrollForm.getOldTicketNumber() != null && !enrollForm.getOldTicketNumber().equals("")) {
//				request.setAttribute("OldTicketNumberNotmustError",	"你不是补考考生，不需要输入原准考证号！");
//				request.setAttribute("enroll", enroll);
//				return mapping.findForward("editEnroll");
//			}
//		}

		// 电话（手机号码）验证
		if (enrollForm.getPhone() == null || enrollForm.getPhone().equals("")) {
			request.setAttribute("PhoneEmptyError", "请输入手机号码！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		} else {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			Matcher m = p.matcher(enrollForm.getPhone());
			if (!m.matches()) {
				request.setAttribute("PhoneInputError", "你输入手机号码错误！");
				request.setAttribute("enroll", enroll);
				return mapping.findForward("editEnroll");
			}
		}

		// 联系地址（所在院系）验证
		if (enrollForm.getDeptId() == 0) {
			request.setAttribute("dept_idEmptyError", "请输入联系地址（所在院系）！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		}

		// 班级验证
		if (enrollForm.getClazzId() == 0) {
			request.setAttribute("clazzEmptyError", "请选择所在班级！");
			request.setAttribute("enroll", enroll);
			return mapping.findForward("editEnroll");
		} 
		
		// 将用户提交的修改数据复制到enroll对象中
		PropertyUtils.copyProperties(enroll, enrollForm);	

		//去掉姓名前后的空格
		enroll.setName(enrollForm.getName().trim());
		
		// 单独修改报考等级和所属院系及所属班级
		enroll.setRank(examService.findRankById(enrollForm.getRank_id()));
		enroll.setDept(managementService.findDepartmentById(enrollForm.getDeptId()));
		enroll.setClazz(managementService.findClazzById(enrollForm.getClazzId()));
		
		// 将考生上传照片保存到photo文件夹中
		String dirPath = request.getSession().getServletContext().getRealPath("/photo");

		// 判断路径是否存在，如果不存在，就创建这个路径
		File fileDir = new File(dirPath);
		if (!fileDir.exists()) {
			fileDir.mkdir();
		}
		
		// 获取文件并存储
		Hashtable<Object, Object> files = form.getMultipartRequestHandler().getFileElements();
			
		for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();

			try {
				FormFile formFile = (FormFile) files.get(key);
				String fileName = formFile.getFileName().trim();// 获得待上传的文件名
				
				if (fileName == null || fileName.equals("")) {
					request.setAttribute("imageEmptyError", "请按要求上传照片！");
					request.setAttribute("enroll", enroll);
					return mapping.findForward("editEnroll");
				} else {
					//删除原相片	
					File file = new File(dirPath+File.separator+enroll.getIcon());
					if (file != null) {
						file.delete();
					}
												
					String icon = null;
					// 保存后的文件名不能使用原来的,可以防止下载出错
					// 新文件名为网报号，待考生交费确认后，将文件名改为报名号
					String rndName ="";
					Random rnd = new Random();
					 for (int i = 0; i < 10; i++) {
						 rndName += rnd.nextInt(10);
					 }
					 //获得当天日期
					 Date date = new Date();
					 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
					 String datetime = sdf.format(date);
					 
					String newFileName = datetime+rndName;
	
					// 读出原文件的扩展名
					String ext = "";
					int pos = fileName.lastIndexOf(".");
					ext = fileName.substring(pos);// 得到扩展名
	
					if (!ext.equalsIgnoreCase(".jpg")) {
						request.setAttribute("imgFormatError", "照片格式不对，只能是jpg格式！");
						request.setAttribute("enroll", enroll);
						return mapping.findForward("editEnroll");
					}
	
					// 拼出完整的新文件名
					// newFileName = datetime + newFileName +
					// ext;//暂时先将报名号作为上传相片的文件名
					newFileName = newFileName + ext;
					icon = newFileName;
	
					InputStream is = formFile.getInputStream();
					OutputStream os = new FileOutputStream(dirPath+ File.separatorChar + newFileName);
	
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					while ((bytesRead = is.read(buffer)) != -1) {
						os.write(buffer, 0, bytesRead);
					}
					os.flush();
	
					is.close();
					os.close();
					enroll.setIcon(icon);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			
		}

		// 修改考生的身份证号码
		Examinee examinee = enroll.getExaminee();
		examinee.setIdCard(enrollForm.getIdCard());
		examService.updateExaminee(examinee);

		// 完成报名信息的修改操作
		examService.updateEnroll(enroll);
		
		// 将考生姓名和报名号发送到报名成功页面
//		Rank rank = examService.findRankById(enrollForm.getRank_id());
//		Department dept = managementService.findDepartmentById(enrollForm.getDeptId());
		
		request.setAttribute("name", enrollForm.getName().trim());
		request.setAttribute("serialNumber", enroll.getExaminee().getSerialNumber());
		request.setAttribute("icon", enroll.getIcon());
		request.setAttribute("rank", enroll.getRank().getName());
		request.setAttribute("idCard", enrollForm.getIdCard());
		request.setAttribute("sex", enrollForm.getSex() == 1 ? "男" : "女");
		request.setAttribute("birthday", enrollForm.getBirthday());
		request.setAttribute("nation", enrollForm.getNation());
		request.setAttribute("profession", enrollForm.getProfession());
		request.setAttribute("degree", enrollForm.getDegree());
		request.setAttribute("phone", enrollForm.getPhone());
		request.setAttribute("department", enroll.getDept().getDeptName());
		request.setAttribute("clazz", enroll.getClazz().getClazzId());
		
		return mapping.findForward("updateEnrollSave");
	}

}
